#!/bin/bash

# 下载脚本wget 
# sudo wget https://gitee.com/newwangsong/analyse-update/raw/master/fix-system.sh

# 公司内网执行脚本
# sudo bash -c "$(wget -O- --no-check-certificate https://172.20.191.209/wangsong/analyse-problem/-/raw/master/fix-system.sh)"

# 外网执行脚本 
# sudo bash -c "$(wget -O- --no-check-certificate https://gitee.com/newwangsong/analyse-update/raw/master/fix-system.sh)"

export DEBIAN_FRONTEND=noninteractive

APPNAME=$(basename "$0" | sed "s/\.sh$//")
MACHINE_ARCH=$(arch)

CONFIG_FILE=""
CONFIG_FILE_OLD="/usr/share/kylin-update-desktop-config/data/kylin-update-desktop-system.json"
# CONFIG_FILE_NEW="/usr/share/kylin-update-desktop-config/config/kylin-update-desktop-system.json"
CONFIG_FILE_TMP="/tmp/update-desktop-config/kylin-update-desktop-system.json"

APT_CONFIG="/tmp/apt-fix.conf"
APT_PRIORITY_CONFIG="/tmp/apt-priority.pref"
SOURCES_PATH="/tmp/sources.list"
CONFIG_FILE_TMP_DIR="/tmp/update-desktop-config/"

APT_RUN="apt-get -c $APT_CONFIG"
REMOVE_PKG_LIMIT=10

TRUE=true
FALSE=false

# -----------------------------------------------------------------------------
# Log functions
# -----------------------------------------------------------------------------

BOLD="$(tput bold 2>/dev/null || printf '')"
GREY="$(tput setaf 0 2>/dev/null || printf '')"
UNDERLINE="$(tput smul 2>/dev/null || printf '')"
RED="$(tput setaf 1 2>/dev/null || printf '')"
GREEN="$(tput setaf 2 2>/dev/null || printf '')"
YELLOW="$(tput setaf 3 2>/dev/null || printf '')"
BLUE="$(tput setaf 4 2>/dev/null || printf '')"
MAGENTA="$(tput setaf 5 2>/dev/null || printf '')"
NO_COLOR="$(tput sgr0 2>/dev/null || printf '')"

info() {
    if [ "$OUTPUT_FILE" = "$TRUE" ]; then
        printf '%s\n\n' "${BOLD}${GREY}>${NO_COLOR} $*" | tee >> $ERROR_DESC_FILE
    else
        printf '%s\n\n' "${BOLD}${GREY}>${NO_COLOR} $*" 
    fi
}

warn() {
    if [ "$OUTPUT_FILE" = "$TRUE" ]; then
        printf '%s\n' "${YELLOW}! $*${NO_COLOR}" | tee >> $ERROR_DESC_FILE
    else
        printf '%s\n' "${YELLOW}! $*${NO_COLOR}"
    fi
}

error() {
    if [ "$OUTPUT_FILE" = "$TRUE" ]; then
        printf '%s\n\n' "${BOLD}> $*${NO_COLOR}" | tee >> $ERROR_DESC_FILE
    else
        printf '%s\n\n' "${BOLD}> $*${NO_COLOR}"
    fi
}

completed() {
  printf '%s\n' "${GREEN}✓${NO_COLOR} $*"
}

# -----------------------------------------------------------------------------
# 检查系统版本：2107、2203
# -----------------------------------------------------------------------------
CURRENT_SYSTEM_VERSION=""
SYSTEM_VERSION_2203="2203"
SYSTEM_VERSION_2107="2107"
#step2: 进一步比较包列表是否满足要求,列表的包都已安装且均大于等于指定版本时为2203系统,退出0,否则退出1'''
CMP_PACKAGES_VERSION=(
    "systemd=245.4-4kylin3.11k30"
)

if [ -f "/etc/os-release" ]; then
    release_id=$(grep -E "^KYLIN_RELEASE_ID=" /etc/os-release | cut -d'"' -f2)
    if [ "$release_id" = "$SYSTEM_VERSION_2203" ]; then
        for item in "${CMP_PACKAGES_VERSION[@]}"; do
            package="${item%=*}"
            required_version="${item#*=}"
            # 检查系统中是否安装了该软件包
            if dpkg-query -W "$package" >/dev/null 2>&1; then
                # 获取系统中已安装的版本号
                installed_version=$(dpkg-query -W -f='${Version}' "$package")

                # 比较版本号
                if dpkg --compare-versions "$installed_version" "ge" "$required_version"; then
                    SYSTEM_VERSION=$SYSTEM_VERSION_2203
                else
                    SYSTEM_VERSION=$SYSTEM_VERSION_2107
                    break
                fi
            else
                SYSTEM_VERSION=$SYSTEM_VERSION_2107
                break
            fi
        done
    else
        SYSTEM_VERSION=$SYSTEM_VERSION_2107
    fi
else
    SYSTEM_VERSION=$SYSTEM_VERSION_2107
fi

# -----------------------------------------------------------------------------
# daq上报日志模块
# -----------------------------------------------------------------------------
TIMEOUT_DURATION=5
CURRENT_DIR=$(pwd)
ANALYSE_DIR="$CURRENT_DIR/analyse-problem"
uploadMessageFile="$ANALYSE_DIR/uploadMessage.py"

if [ -d "$ANALYSE_DIR" ]; then
    rm -rf "$ANALYSE_DIR"
fi

if [ ! -d "$ANALYSE_DIR" ]; then
    mkdir -p "$ANALYSE_DIR"
fi

DAQ_STATUS="$TRUE"

fn_env_daq_upload_log() {
    MACHINE_ARCH=$(arch)
    DAQ_DEB_PATH="$ANALYSE_DIR/deb/"
    
    if [ ! -d "$DAQ_DEB_PATH" ]; then
        mkdir -p "$DAQ_DEB_PATH"
    fi

    if [ -f "$uploadMessageFile" ]; then
        rm -f "$uploadMessageFile"
    fi

    timeout "$TIMEOUT_DURATION" wget --no-check-certificate -P "$ANALYSE_DIR" https://gitee.com/newwangsong/analyse-update/raw/master/uploadMessage.py

    if [[ $? != 0 ]];then
        printf '%s\n' "获取uploadMessage.py失败，请检查网络"
        DAQ_STATUS="$FALSE"
    fi

    if [ "$DAQ_STATUS" == "$TRUE" ]; then
        case "$MACHINE_ARCH" in
            x86_64)
                timeout "$TIMEOUT_DURATION" wget --no-check-certificate -P "$ANALYSE_DIR" https://gitee.com/newwangsong/analyse-update/raw/master/kylin-daq_1.2.8.1-0k2.10_amd64.deb
                DEB_PATH="$ANALYSE_DIR/kylin-daq_1.2.8.1-0k2.10_amd64.deb"
                ;;
            aarch64)
                timeout "$TIMEOUT_DURATION" wget --no-check-certificate -P "$ANALYSE_DIR" https://gitee.com/newwangsong/analyse-update/raw/master/kylin-daq_1.2.8.1-0k2.10_arm64.deb
                DEB_PATH="$ANALYSE_DIR/kylin-daq_1.2.8.1-0k2.10_arm64.deb"
                ;;
            mips64)
                timeout "$TIMEOUT_DURATION" wget --no-check-certificate -P "$ANALYSE_DIR" https://gitee.com/newwangsong/analyse-update/raw/master/kylin-daq_1.2.8.1-0k2.10_mips64el.deb
                DEB_PATH="$ANALYSE_DIR/kylin-daq_1.2.8.1-0k2.10_mips64el.deb"
                ;;
            loongarch64)
                timeout "$TIMEOUT_DURATION" wget --no-check-certificate -P "$ANALYSE_DIR" https://gitee.com/newwangsong/analyse-update/raw/master/kylin-daq_1.2.8.1-0k2.10_loongarch64.deb
                DEB_PATH="$ANALYSE_DIR/kylin-daq_1.2.8.1-0k2.10_loongarch64.deb"
                ;;
            *)
                DEB_PATH=""
                ;;
        esac

        if [[ $? != 0 ]];then
            printf '%s\n' "获取kylin-daq失败，请检查网络"
            DAQ_STATUS="$FALSE"
        fi

        if [ "$DAQ_STATUS" == "$TRUE" ]; then
            if [ -f "$DEB_PATH" ]; then
                dpkg -i "$DEB_PATH"
            fi

            if [[ $? != 0 ]];then
                printf '%s\n' "安装kylin-daq失败"
                DAQ_STATUS="$FALSE"
            fi
        fi
    fi
}

# -----------------------------------------------------------------------------
# 从平台获取update_desktop_config配置
# -----------------------------------------------------------------------------
fn_get_update_desktop_config() {
    TEMPLATE_AMD64_DIR="$ANALYSE_DIR/template/amd64"
    TEMPLATE_ARM64_DIR="$ANALYSE_DIR/template/arm64"
    TEMPLATE_MIPS64_DIR="$ANALYSE_DIR/template/mips64el"
    TEMPLATE_LOONGARCH64_DIR="$ANALYSE_DIR/template/loongarch64"

    MACHINE_ARCH=$(arch)
    case "$MACHINE_ARCH" in
        x86_64)
            mkdir -p "$TEMPLATE_AMD64_DIR"
            timeout "$TIMEOUT_DURATION" wget --no-check-certificate -P "$TEMPLATE_AMD64_DIR" https://gitee.com/newwangsong/analyse-update/raw/master/template/amd64/kylin-update-desktop-system.json
            ;;
        aarch64)
            mkdir -p "$TEMPLATE_ARM64_DIR"
            timeout "$TIMEOUT_DURATION" wget --no-check-certificate -P "$TEMPLATE_ARM64_DIR" https://gitee.com/newwangsong/analyse-update/raw/master/template/arm64/kylin-update-desktop-system.json
            ;;
        mips64)
            mkdir -p "$TEMPLATE_MIPS64_DIR"
            timeout "$TIMEOUT_DURATION" wget --no-check-certificate -P "$TEMPLATE_MIPS64_DIR" https://gitee.com/newwangsong/analyse-update/raw/master/template/mips64el/kylin-update-desktop-system.json
            ;;
        loongarch64)
            mkdir -p "$TEMPLATE_LOONGARCH64_DIR"
            timeout "$TIMEOUT_DURATION" wget --no-check-certificate -P "$TEMPLATE_LOONGARCH64_DIR" https://gitee.com/newwangsong/analyse-update/raw/master/template/loongarch64/kylin-update-desktop-system.json
            ;;
        *)
            printf '%s\n' "Unknown architecture: $MACHINE_ARCH"
            upload_error_mesage_to_php "获取kylin-update-desktop-config配置文件" "未匹配到本地架构信息"
            exit 102
            ;;
    esac

    if [[ $? != 0 ]];then
        printf '%s\n' "获取kylin-update-desktop-config配置文件失败，请检查网络"
        upload_error_mesage_to_php "获取kylin-update-desktop-config配置文件" "获取配置文件失败，请检查网络"
        exit 102
    fi

    upload_error_mesage_to_php "获取kylin-update-desktop-config配置文件" "获取配置文件成功"
}

# -----------------------------------------------------------------------------
# 释放update_desktop_config文件至/tmp/update-desktop-config/kylin-update-desktop-system.json
# -----------------------------------------------------------------------------
fn_make_update_desktop_config() {
    if [ ! -d "$CONFIG_FILE_TMP_DIR" ]; then
        mkdir -p "$CONFIG_FILE_TMP_DIR"
    fi

    SOURCE_FILE=""
    CURRENT_DIR=$(pwd)
    case "$MACHINE_ARCH" in
        x86_64)
            echo "System architecture is ($MACHINE_ARCH)"
            SOURCE_FILE="$ANALYSE_DIR/template/amd64/kylin-update-desktop-system.json"
            ;;
        aarch64)
            echo "System architecture is ($MACHINE_ARCH)"
            SOURCE_FILE="$ANALYSE_DIR/template/arm64/kylin-update-desktop-system.json"
            ;;
        mips64)
            echo "System architecture is ($MACHINE_ARCH)"
            SOURCE_FILE="$ANALYSE_DIR/template/mips64el/kylin-update-desktop-system.json"
            ;;
        loongarch64)
            echo "System architecture is ($MACHINE_ARCH)"
            SOURCE_FILE="$ANALYSE_DIR/template/loongarch64/kylin-update-desktop-system.json"
            ;;
        *)
            echo "Unknown architecture: $MACHINE_ARCH"
            ;;
    esac

    cp "$SOURCE_FILE" "$CONFIG_FILE_TMP"
}

# -----------------------------------------------------------------------------
# 检查系统软件包环境
# -----------------------------------------------------------------------------
fn_make_sources() {
    #根据版本2107或2303使用不同的源
    if [ "$SYSTEM_VERSION" = "$SYSTEM_VERSION_2107" ]; then
        info "${BOLD}当前系统为2107系统替换相应源...${NO_COLOR}"
        cat > $SOURCES_PATH <<EOF
deb http://archive.kylinos.cn/kylin/KYLIN-ALL 10.1-2107-updates main restricted
deb http://archive2.kylinos.cn/deb/kylin/production/PART-V10-SP1/custom/partner/V10-SP1 default all universe multiverse
deb http://archive.kylinos.cn/kylin/KYLIN-ALL 10.1 main restricted universe multiverse
EOF
    else
        info "${BOLD}当前系统为2203系统替换相应源...${NO_COLOR}"
        cat > $SOURCES_PATH <<EOF
deb http://archive2.kylinos.cn/deb/kylin/production/PART-V10-SP1/custom/partner/V10-SP1 default all
deb http://archive.kylinos.cn/kylin/KYLIN-ALL 10.1 main restricted universe multiverse
deb http://archive.kylinos.cn/kylin/KYLIN-ALL 10.1-2203-updates main universe restricted multiverse
EOF
    fi
}

# -----------------------------------------------------------------------------
# 设置apt修复时使用的配置，包括调整优先级设置到允许降级、禁止安装推荐和建议软件包、默认保留旧配置、允许降级、不更新非系统标准源
# -----------------------------------------------------------------------------
fn_make_tmp_config() {
    # 创建调整源优先级配置 统一允许降级
	cat > $APT_PRIORITY_CONFIG <<EOF
# 将调整所有的源优先级 允许使用降级
# 参考文档https://manpages.debian.org/bookworm/apt/apt_preferences.5.en.html
Package: *
Pin: origin "*"
Pin-Priority: 1001
EOF

    # 创建apt配置
	cat > $APT_CONFIG <<EOF
APT::Install-Recommends "false";
APT::Install-Suggests "false";
Dir::Etc::sourceparts "";
DPkg::Post-Invoke "";
APT::Get::allow-downgrades "true";
APT::Get::allow-change-held-packages "true";
Dir::Etc::sourcelist "$SOURCES_PATH";

Dpkg::Options {
	      "--force-confold";
	      "--force-confdef";
}
Dir::Etc::preferences "$APT_PRIORITY_CONFIG";
EOF
}

# -----------------------------------------------------------------------------
# 检查修复是否删除重要软件包，判断逻辑，首先检查config包中install_list 移除软件包是否在此列表在直接退出
# -----------------------------------------------------------------------------
check_remove_essential() {
    PACKAGES=$1
    # 获取修复时被移除的包列表
    REMOVE_PACKAGES=($($APT_RUN install $PACKAGES -y --simulate 2>&1 | grep '^Remv' | awk '{print $2}' | tr '\n' ' '))
    if [ -n "$REMOVE_PACKAGES" ]; then
        warn "${BOLD}下列软件包将被【卸载】: ${REMOVE_PACKAGES[@]} ${NO_COLOR}"
        
        if [ -f "$CONFIG_FILE" ]; then
            install_list=$(jq -r '.install_list' "$CONFIG_FILE")

            # 强制移除存在异常的软件包脚本 来修复系统环境
            for pkg_name in "${REMOVE_PACKAGES[@]}"; do
                if [[ "$install_list" == *"$pkg_name"* ]]; then
                    echo "警告：系统必须的软件包($pkg_name)被移除"
                    if [[ "$pkg_name" == "ukui-clock" && "$MACHINE_ARCH" == "loongarch64" && "$SYSTEM_VERSION" == "$SYSTEM_VERSION_2107" ]]; then
                        echo "ukui-clock在2107 loongarch64下不被保留"
                    elif [[ "$pkg_name" == "ukui-notebook" && "$MACHINE_ARCH" == "loongarch64" && "$SYSTEM_VERSION" == "$SYSTEM_VERSION_2107" ]]; then
                        echo "ukui-notebook在2107 loongarch64下不被保留"
                    else
                        exit 100
                    fi
                fi
            done
        else
            remove_size=${#REMOVE_PACKAGES[@]}
            if [ "$remove_size" -gt $REMOVE_PKG_LIMIT ]; then
                echo "警告：删除软件包数量超过5个 不允许删除，若判断删除没有影响，则添加参数 --force 强制执行"
                exit 100
            fi
        fi
    fi
}

# -----------------------------------------------------------------------------
# 正在校验系统版本与产品线
# -----------------------------------------------------------------------------
#大于等于左侧版本，小于等于右侧版本判断属于2107和2203系统
CMP_PACKAGES_VERSION_LEGE=(
    "245.4-4kylin3k6=systemd=245.4-4kylin3.11k30"
)

BUILDID_VERSION=(
    "31950" "31949" "31951" "31952" "36193" "36194" "36195" "36196"
    "37281" "37282" "37283" "37284" "38110" "38109" "38111" "38112"
    "41380" "33852"
)

check_system_version_correct() {
    hardware_info=$(grep '^Hardware' /proc/cpuinfo | awk -F ': ' '{print $2}')

    if [[ $hardware_info == *"Kirin"* && $hardware_info == *"990"* ]]; then
        printf '%s\n' "本脚本不应在 wayland 环境下执行，如有需要请联系相关研发人员"
        upload_error_mesage_to_php "校验系统版本与产品线" "本脚本不应在wayland环境下执行"
        exit 101
    fi

    if [[ $hardware_info == *"Kirin"* && $hardware_info == *"9006c"* ]]; then
        printf '%s\n' "本脚本不应在 wayland 环境下执行，如有需要请联系相关研发人员"
        upload_error_mesage_to_php "校验系统版本与产品线" "本脚本不应在wayland环境下执行"
        exit 101
    fi

    if pidof "ukui-kwin_wayland" > /dev/null; then
        printf '%s\n' "本脚本不应在 wayland 环境下执行，如有需要请联系相关研发人员"
        upload_error_mesage_to_php "校验系统版本与产品线" "本脚本不应在wayland环境下执行"
        exit 101
    fi

    model_name=$(grep 'model name' /proc/cpuinfo | head -n 1 | awk -F ': ' '{print $2}')
    if [[ $model_name == *"Intel"* ]]; then
        printf '%s\n' "本脚本不应在 Intel 环境下执行，如有需要请联系相关研发人员"
        upload_error_mesage_to_php "校验系统版本与产品线" "本脚本不应在Intel环境下执行"
        exit 101
    fi

    #判断kylin build id
    BUILDID=""
    BUILDID_CORRENT="$FALSE"
    if [ -f "/etc/kylin-build" ]; then
        BUILDID=$(grep "^buildid: " /etc/kylin-build | awk -F ': ' '{print $2}' | tr -d ' ')
        for id_item in "${BUILDID_VERSION[@]}"; do
            # printf '%s\n' "BUILDID: $BUILDID, id_item: $id_item"
            if [ "$BUILDID" == "$id_item" ]; then
                BUILDID_CORRENT="$TRUE"
                CURRENT_SYSTEM_VERSION="2203"
            fi
        done
        
        if [ "$BUILDID_CORRENT" == "$FALSE" ]; then
            BUILDID_2107=$(grep -E "^Build " /etc/kylin-build | awk -F ' ' '{print $2}')
            echo "$BUILDID_2107"

            if [[ "$BUILDID_2107" == "20210722" || "$BUILDID_2107" == "20210531" ]]; then
                BUILDID_CORRENT="$TRUE"
                CURRENT_SYSTEM_VERSION="2107"
            elif [[ "$BUILDID_2107" == "20210922" && "$MACHINE_ARCH" == "loongarch64" ]]; then
                BUILDID_CORRENT="$TRUE"
                CURRENT_SYSTEM_VERSION="2107"
            elif [[ "$BUILDID_2107" == "20210521" && "$MACHINE_ARCH" == "loongarch64" ]]; then
                BUILDID_CORRENT="$TRUE"
                CURRENT_SYSTEM_VERSION="2107"
            fi
        fi
    fi

    if [ "$BUILDID_CORRENT" == "$FALSE" ]; then
        printf '%s\n' "本脚本不应在 ($BUILDID | $BUILDID_2107) 环境下执行，如有需要请联系相关研发人员"
        upload_error_mesage_to_php "校验系统版本与产品线" "本脚本不应在($BUILDID|$BUILDID_2107)环境下执行"
        exit 101
    fi

    for item in "${CMP_PACKAGES_VERSION_LEGE[@]}"; do
        left_version=$(echo "$item" | cut -d '=' -f 1)
        package=$(echo "$item" | cut -d '=' -f 2)
        right_version=$(echo "$item" | cut -d '=' -f 3)

        # echo "111 $left_version $package $right_version"
        # 检查系统中是否安装了该软件包
        if dpkg-query -W "$package" >/dev/null 2>&1; then
            # 获取系统中已安装的版本号
            installed_version=$(dpkg-query -W -f='${Version}' "$package")

            if dpkg --compare-versions "$installed_version" "ge" "$left_version"; then
                if dpkg --compare-versions "$installed_version" "le" "$right_version"; then
                    printf '%s\n' "$left_version:$installed_version:$right_version"
                else
                    printf '%s\n%s' "本脚本不应在 非2107、2203 环境下执行，如有需要请联系相关研发人员" "$package=$installed_version"
                    upload_error_mesage_to_php "校验系统版本与产品线" "本脚本不应在非2107、2203环境下执行，如有需要请联系相关研发人员"
                    exit 101
                fi
            else
                printf '%s\n%s'" 本脚本不应在 非2107、2203 环境下执行，如有需要请联系相关研发人员" "$package=$installed_version"
                upload_error_mesage_to_php "校验系统版本与产品线" "本脚本不应在非2107、2203环境下执行，如有需要请联系相关研发人员"
                exit 101
            fi
        else
            printf '%s\n' "$package 未安装，本脚本不应在 非2107、2203 环境下执行，如有需要请联系相关研发人员"
            upload_error_mesage_to_php "校验系统版本与产品线" "$package未安装，本脚本不应在,非2107、2203环境下执行，如有需要请联系相关研发人员"
            exit 101
        fi
    done
}

# -----------------------------------------------------------------------------
# 校验激活包版本信息是否正确
# -----------------------------------------------------------------------------
check_activation_version_correct() {
    ACTIVATION_CORRENT="$TRUE"
    if dpkg-query -W "kylin-activation" >/dev/null 2>&1; then

        installed_activation_version=$(dpkg-query -W -f='${Version}' "kylin-activation")

        if dpkg --compare-versions "$installed_activation_version" "ge" "1.3.11.1-0k0.9"; then
            if dpkg --compare-versions "$installed_activation_version" "le" "1.3.11.1-0k1.5"; then

                installed_libactivation_version=$(dpkg-query -W -f='${Version}' "libkylin-activation")

                if dpkg --compare-versions "$installed_libactivation_version" "le" "3.0.0.1-0k0.1"; then
                    ACTIVATION_CORRENT="$FALSE"
                fi
            fi
        fi
    fi

    if [ "$ACTIVATION_CORRENT" == "$FALSE" ]; then
        printf 'kylin-activation、libkylin-activation版本检测异常\n'
    else
        printf 'kylin-activation、libkylin-activation版本检测正常\n'
    fi
}

# -----------------------------------------------------------------------------
# 配置显示不同的显色
# -----------------------------------------------------------------------------

fn_display_usage() {
	echo "Usage: $(basename "$0") [OPTION]..."
	echo ""
	echo "Options"
    echo ""
	echo " -c, --check            仅检查系统环境并显示异常软件包。"
	echo " -r, --run              运行修复系统环境"
    echo ""
	echo " -y                     自动执行不需要确认。"
	echo " -s, --simulate         模拟执行，不进行实际修复操作。"
	echo " -f, --force            强制进行修复，忽略任何警告。"
	echo ""
	echo "更多帮助信息, 请查看README文件:"
	echo ""
	echo "https://gitee.com/newwangsong/fix-tool/blob/master/README.md"
}

fn_check_pkg_in_cache() {
    # 过滤出可以安装的软件包
    echo "正在检查那些软件包在Cache内..."
    PACKAGES=$1
    AVAILABLE_PACKAGES=""
    for PACKAGE in $PACKAGES; do
        if grep -h "^Package: " /var/lib/apt/lists/*_Packages | grep -q "^Package: $PACKAGE"; then
            AVAILABLE_PACKAGES="$AVAILABLE_PACKAGES $PACKAGE"
            echo "Package $PACKAGE exists in the repository."
        else
            echo "Package $PACKAGE does not exist in the repository."
        fi
    done
    echo "$AVAILABLE_PACKAGES"
}

upload_error_mesage_to_php() {
    #获取修复阶段及结果 （修复前，修复成功，修复失败）
    fixStatus=$1
    #错误原因
    failResult=$2

    execResult=$2

    python3 "$uploadMessageFile" "$fixStatus" "$failResult" "$execResult" || true

    #获取系统版本
    systemVersion=`cat /etc/kylin-build |grep buildid | awk -F ':' '{print $2}'| tr -d ' '`
    if [ -z "$systemVersion" ]; then
        systemVersion=`cat /etc/os-release |grep KYLIN_RELEASE_ID | awk -F '=' '{print $2}'| tr -d ' '`
        if [ -z "$systemVersion" ]; then
            systemVersion=`cat /etc/kylin-build |grep Build | awk '{print $2}' | tr -d ' '`
        fi
    fi
    #获取补丁版本
    patchVersion=`cat /etc/kylin-version/kylin-system-version.conf |grep update_version | awk -F '=' '{print $2}'| tr -d ' '`

    #获取mac地址
    mac=`cat /sys/class/net/$(ip route show default | awk '/default/ {print $5}')/address`

    #获取服务序列号
    serialNumber=`cat /etc/.kyinfo |grep key= | awk -F '=' '{print $2}' | tr -d ' '`

    datetime=`LANG=en_US date | tr -d ' '`

    url="http://archive1.kylinos.cn:32294/kylin-update-manager-server/main-1.php?host_mac=$mac&datetime=$datetime&serial_number=$serialNumber&errorcode=$failResult&status=$fixStatus&appname=$systemVersion&appversion=$patchVersion"

    printf '\n'
    wget -q $url
    printf '\n'
}

main() {
    fn_env_daq_upload_log

    info "${BOLD}正在校验系统版本与产品线...${NO_COLOR}"
    check_system_version_correct

    check_activation_version_correct

    info "${BOLD}正在创建必须的配置和源信息...${NO_COLOR}"
    fn_make_tmp_config
    fn_make_sources

    info "${BOLD}进行apt update检查更新中，请稍后...${NO_COLOR}"
    $APT_RUN update >/dev/null 2>&1

    info "${BOLD}正在安装必要的工具...${NO_COLOR}"
    $APT_RUN install -y jq >/dev/null

    # 模拟运行 dist-upgrade 并保存输出
    info "${BOLD}提取将被降级的软件包...${NO_COLOR}"
    UPGRADE_INFO=$(LANG= echo N | LANG= apt-get -c $APT_CONFIG dist-upgrade)
    DOWNGRADED_PACKAGES=$(echo "$UPGRADE_INFO" | awk '/The following packages will be DOWNGRADED:/,/^$/{if ($0 ~ /  /) print $0}' | tr -d ',' | tr '\n' ' ')

    if [ "$SYSTEM_VERSION" = "$SYSTEM_VERSION_2107" ]; then
        info "${BOLD}获取kylin-update-desktop-config配置文件...${NO_COLOR}"
        fn_get_update_desktop_config
        fn_make_update_desktop_config
    else
        CONFIG_FILE_TMP=""
        info "${BOLD}安装必要的配置包kylin-update-desktop-config...${NO_COLOR}"
        $APT_RUN reinstall kylin-update-desktop-config -y >/dev/null
    fi

    if [ -f "$CONFIG_FILE_TMP" ]; then
        CONFIG_FILE=$CONFIG_FILE_TMP
    elif [ -f "$CONFIG_FILE_NEW" ]; then
        CONFIG_FILE=$CONFIG_FILE_NEW
	else
        CONFIG_FILE=$CONFIG_FILE_OLD
    fi

    info "${BOLD}解析需要安装和升级的软件包...${NO_COLOR}"
    INSTALL_LIST=$(jq -r '.install_list | join(" ")' "$CONFIG_FILE")

    UPGRADE_LIST=$(jq -r '.upgrade_list | join(" ")' "$CONFIG_FILE")

    info "${BOLD}检查在Cache内的软件包...${NO_COLOR}"
    AVAILABLE_INSTALL=""
    for PACKAGE in $INSTALL_LIST; do
        if grep -h "^Package: " /var/lib/apt/lists/*_Packages | grep -q "^Package: $PACKAGE$"; then
            AVAILABLE_INSTALL="$AVAILABLE_INSTALL $PACKAGE"
        fi
    done

    # 查找可升级的包列表
    AVAILABLE_UPGRADE=""
    system_upgrade_list=$(apt list --upgradable 2>/dev/null | awk '{print $1}')
    # 遍历列表，打印出交集
    for PACKAGE in $UPGRADE_LIST; do
        if echo "$system_upgrade_list" | grep -q "\<$PACKAGE\>"; then
            AVAILABLE_UPGRADE="$AVAILABLE_UPGRADE $PACKAGE"
        fi
    done

    info "${BOLD}检查移除重要软件包...${NO_COLOR}"
    check_remove_essential "$AVAILABLE_INSTALL $AVAILABLE_UPGRADE"

    $APT_RUN install $AVAILABLE_INSTALL  $AVAILABLE_UPGRADE $DOWNGRADED_PACKAGES
    if [[ $? != 0 ]]; then
        warn "${BOLD}系统环境修复失败，如有需要请联系相关研发人员 ${NO_COLOR}"
        upload_error_mesage_to_php "系统环境修复结束" "系统环境修复失败"
    else
        info "${BOLD}系统环境修复成功 ${NO_COLOR}"
        upload_error_mesage_to_php "系统环境修复结束" "系统环境修复成功"
    fi

    # output=$($APT_RUN install $AVAILABLE_INSTALL  $AVAILABLE_UPGRADE $DOWNGRADED_PACKAGES 2>&1)
    # if [[ $? != 0 ]]; then
    #     printf '%s\n' "$output"
    #     warn "${BOLD}系统环境修复失败，如有需要请联系相关研发人员 ${NO_COLOR}"
    #     cleaned_output=$(echo "$output" | sed 's/[[:space:]\/&#]//g')
    #     upload_error_mesage_to_php "系统环境修复结束" "系统环境修复失败: $cleaned_output"
    # else
    #     printf '%s\n' "$output"
    #     info "${BOLD}系统环境修复成功 ${NO_COLOR}"
    #     upload_error_mesage_to_php "系统环境修复结束" "系统环境修复成功"
    # fi

    check_activation_version_correct
}

main "$@"
